using System;
using System.Configuration;
using System.Globalization;
using System.Web;
using System.Web.Mail;
using System.Web.UI;
using System.Xml;

using log4net;
using WebsiteX.com.msn.search.soap;

/*	-----------------------------------------------------------------------	
	Copyright:	umlungu consulting (pty) ltd
	Author:		Alan Benington
	Started:	2008-06-14
	Status:		release	
	Version:	2.0.0
	Build:		20080614
	License:	GNU General Public License
	-----------------------------------------------------------------------	*/

/*	-----------------------------------------------------------------------	
	Development Notes:
	==================
	20080614:	Initial release.
	---------------------------------------------------------------------------	*/

namespace umlungu.engineX.blogX.WebsiteX {
	/// <summary>
	/// Description of the WebsiteXSearch class.
	/// <para>Additional information about the class</para>
	/// </summary>
	public class WebsiteXSearch : x_broker {
		#region Invisible properties
		private bool testing = false;
		private const string logsep = ",";
		private MSNSearchService webservice;
		private const string LIVE_ID = "0700789A921D1AC4FAC70E1C6BD2074BCFD24814";
		private const string SEARCH_PREFIX = "site:pearlvalley.co.za";
		private const string SEARCH_RESULTS = "<SearchResults/>";
		private const string SEARCH_RESULT = "SearchResult";
		private const string SEARCH_RESULT_XML = "<title/><description/><url/>";
		private const int SEARCH_RESULT_COUNT = 25;
		#endregion

		#region Constant name strings
		private const string logid = "BrokerSearch";
		#endregion

		#region Constant error strings
		private const string error_search = "BrokerSearch error::";
		private const string error_search_search = " Error on search request: ";
		private const string error_search_none = " No results for: '";
		private const string error_search_test = " test error";
		#endregion

		#region Visible properties
		public static readonly ILog Logger = LogManager.GetLogger(typeof(WebsiteXSearch));
		#endregion

		#region Constructors/Destructors
		/// <overloads>Constructor</overloads>
		/// <summary>Default constructor</summary>
		/// <param name="thispage">The web application Page object</param>
		public WebsiteXSearch(displayX thispage) : base(thispage) {
			log4net.Config.XmlConfigurator.Configure();
		}
		#endregion

		#region Public methods
		public override void Process(string type) {
			Logger.Info(String.Concat(logid, "_Process:", type));
			switch (type) {
				case "test":	test();		break;
				case "search":	search();	break;
			}
		}
		public void ProcessContent(XmlElement contel) {
			if (testing)
				test(contel);
			else
				nottest(contel);
		}
		#endregion
		
		#region Protected methods
		#endregion
				
		#region Private methods
		/// <summary>Do search</summary>
		private void search() {
			try {
				if (testing) {
					// test code
					test();
				} else {
					XmlDocument result = liveSearch();
					UIPage.Content.AppendChild(UIPage.Document.ImportNode(result.DocumentElement, true));
				}
				Logger.Info(String.Concat(logid, "_email:"));
			} catch (x_exception e) {
				throw e;
			} catch (Exception e) {
				throw (new x_exception("error_search", String.Concat(error_search, error_search_search, e.Message)));
			}
		}
		#endregion

		#region Live Search methods
		private XmlDocument liveSearch() {
			Logger.Debug(String.Concat("liveSearch:", UIPage.UserProfile.Value("SearchText")));
			XmlDocument results = new XmlDocument();
			results.LoadXml(SEARCH_RESULTS);
			Logger.Debug(String.Concat("liveSearch:", results.OuterXml));

			webservice = new MSNSearchService();
			SearchRequest req = new SearchRequest();
			req.AppID = LIVE_ID;
			SourceRequest[] srcr = new SourceRequest[1];
			srcr[0] = new SourceRequest();
			srcr[0].Source = SourceType.Web;
			srcr[0].Count = SEARCH_RESULT_COUNT;
			srcr[0].Offset = 0;
			req.Requests = srcr;
			req.CultureInfo = "en-us";
			req.Flags = SearchFlags.None;
			req.Query = String.Concat(SEARCH_PREFIX, " ", UIPage.UserProfile.Value("SearchText"));
			req.SafeSearch = SafeSearchOptions.Moderate;
			
            SearchResponse resp = webservice.Search(req);
            Logger.Debug(resp.Responses.Length.ToString());
			foreach (SourceResponse sourceResponse in resp.Responses) {
				Result[] sourceResults = sourceResponse.Results;

				Logger.Debug(String.Concat("liveSearch:", sourceResponse.Total.ToString()));

				if (sourceResponse.Total <= 0)
					throw (new x_exception("error_search_none", String.Concat(error_search, error_search_none, UIPage.UserProfile.Value("SearchText"), "'")));

				results.DocumentElement.SetAttribute("count", (sourceResponse.Total > 0) ? sourceResponse.Total.ToString() : "0");
				foreach (Result sourceResult in sourceResults) {
					string title = ((sourceResult.Title != null) && (sourceResult.Title != String.Empty))? sourceResult.Title : "";
					string description = ((sourceResult.Description != null) && (sourceResult.Description != String.Empty))? sourceResult.Description : "";
					string url = ((sourceResult.Url != null) && (sourceResult.Url != String.Empty))? sourceResult.Url : "";

					Logger.Debug(String.Concat("liveSearch:", title, logsep, description, logsep, url));

					XmlElement resel = results.DocumentElement.AppendChild(results.CreateElement(SEARCH_RESULT)) as XmlElement;
					resel.InnerXml = SEARCH_RESULT_XML;
					resel.SelectSingleNode("title").InnerXml = UIPage.Server.HtmlEncode(title);
					resel.SelectSingleNode("description").InnerXml = UIPage.Server.HtmlEncode(description);
					resel.SelectSingleNode("url").InnerXml = UIPage.Server.HtmlEncode(url);
				}
			}
			Logger.Debug(String.Concat("liveSearch:", results.OuterXml));
			return results;
		}
		#endregion

		#region Private utility methods
		private void test() {
		}
		private void test(XmlElement contel) {
			XmlDocument doc = contel.OwnerDocument;
			XmlNode page = contel.SelectSingleNode("//content/page");
		}
		private void nottest() {
		}
		private void nottest(XmlElement contel) {
			XmlDocument doc = contel.OwnerDocument;
			XmlNode page = contel.SelectSingleNode("//content/page");
		}
		#endregion
	}
}
